import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: (typeof localStorage !== 'undefined' && localStorage.getItem('token')) || '',
    profile: null,
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    async login(form) {
      const { login, getCurrentUserId } = await import('@/services/auth')
      const res = await login(form)
      
      // 登录成功且返回了token
      if (res?.code === 200 && res?.data?.token) {
        // 设置token到状态和localStorage
        this.setToken(res.data.token)
        
        // 增加小延迟确保token完全设置生效
        // 解决token设置和验证的时序问题
        await new Promise(resolve => setTimeout(resolve, 100))
        
        // 尝试获取用户信息，即使失败也不影响登录流程
        try {
          const id = await getCurrentUserId()
          this.profile = { id }
          console.log('登录成功，用户ID:', id)
        } catch (error) {
          console.warn('登录成功但获取用户信息失败:', error.message)
          // 即使获取用户信息失败，也保留token，因为登录本身是成功的
        }
      } else {
        console.error('登录失败:', res?.message || '未知错误')
      }
      
      return res
    },
    setToken(token) {
      this.token = token
      try { token ? localStorage.setItem('token', token) : localStorage.removeItem('token') } catch (_) {}
    },
    setProfile(profile) {
      this.profile = profile
    },
    logout() {
      this.token = ''
      this.profile = null
      try { localStorage.removeItem('token') } catch (_) {}
    },
  },
})


